package bm.com.framework.common.encrypt;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.Base64;

public class Base64Util {

    /**
     * 解密
     *
     * @param value
     * @return
     */
    public static String decry(String value) throws UnsupportedEncodingException {
        byte[] base64decodedBytes = Base64.getDecoder().decode(value);
        return new String(base64decodedBytes, "utf-8");
    }

    /**
     * 加密
     *
     * @param value
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String encrypt(String value) throws UnsupportedEncodingException {
        return Base64.getEncoder().encodeToString(value.getBytes("utf-8"));
    }

    /**
     * 图片转化成 base64
     * @param filePath
     * @return
     */
    public static String imageToBase64String(String filePath){
        if (null == filePath || 0 == filePath.length()){
            throw new RuntimeException("图片路径不能为空！！");
        }
        InputStream in = null;
        byte[] data = null;
        try {
            //读取图片字节数组
            in = new FileInputStream(filePath);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        }catch (IOException e){
            e.printStackTrace();
        }
        StringBuilder sb = new StringBuilder();
        sb.append("data:image/jpg;base64,");
        sb.append(Base64.getEncoder().encodeToString(data));

        //对字节数组Base64编码，返回Base64编码过的字节数组字符串
        return sb.toString();
    }
}
